package com.ym.controller.patient.self;

import com.github.pagehelper.PageInfo;
import com.ym.common.constant.Constants;
import com.ym.core.annotation.ApiSign;
import com.ym.core.annotation.Log;
import com.ym.core.domain.APIResponse;
import com.ym.core.domain.BaseController;
import com.ym.core.exception.BusinessException;
import com.ym.core.shiro.ShiroUtil;
import com.ym.medical.domain.entity.AccountEntity;
import com.ym.medical.domain.entity.PersonalTransactionOrderEntity;
import com.ym.medical.domain.entity.UserEntity;
import com.ym.medical.domain.param.UserSetPwdParam;
import com.ym.medical.domain.vo.AccountVo;
import com.ym.medical.domain.vo.DoctorTdDetailsVO;
import com.ym.medical.domain.vo.UserExpendIncomeVO;
import com.ym.medical.enums.CodeRuleEnum;
import com.ym.medical.enums.PaymentStateEnum;
import com.ym.medical.enums.TransactionDetailsTdTypeEnum;
import com.ym.medical.enums.TransactionStateEnum;
import com.ym.medical.service.IAccountSV;
import com.ym.medical.service.IConsumeDetailsSV;
import com.ym.medical.service.IPersonalTransactionOrderSV;
import com.ym.medical.service.ISysCodeRuleSV;
import com.ym.medical.service.IUserSV;
import com.ym.spring.SessionContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * 我的账户
 *
 * @author: 李涛
 * @version: 2019年05月14日 19:35
 */
@Api(tags = "患者端-我的账户")
@RestController
@ApiSign
@RequestMapping(value = "/patient/self/account", headers = Constants.Api.VERSION)

public class MyAccountController extends BaseController {

	@Autowired
	private IConsumeDetailsSV consumeDetailsSV;

	@Autowired
	private IAccountSV accountSV;

	@Autowired
	private IPersonalTransactionOrderSV personalTransactionOrderSV;

	@Autowired
	private ISysCodeRuleSV generateCodeRuleSV;

	@Autowired
	private IUserSV userSV;


	@ApiOperation("患者端-账户余额")
	@GetMapping(value = "/account/balance")
	public APIResponse<AccountVo> accountBalance() {
		/** 获取当前用户的id*/
		Long userId = ShiroUtil.getLoginId();
		AccountVo account = accountSV.selectAccount(userId);
		if (account == null) {
			return failMsg("不存在该账户！");
		}
		return successData(account);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("患者端-账户交易明细")
	@GetMapping(value = "/consume/detail")
	public APIResponse<UserExpendIncomeVO> transactionDetail(@RequestParam(required = false) String tdTime,
															 @RequestParam(defaultValue = "1", required = false) int pageNum,
															 @RequestParam(defaultValue = "5") int pageSize) {
		Long userId = ShiroUtil.getLoginId();
		PageInfo<DoctorTdDetailsVO> doctorTdDetailsVOPageInfo = consumeDetailsSV.userTransactionDetail(userId, tdTime, pageNum, pageSize);
		UserExpendIncomeVO patientExpendIncome = consumeDetailsSV.patientExpendIncome(userId, tdTime);
		patientExpendIncome.setDoctorTdDetailsVOS(doctorTdDetailsVOPageInfo);
		return successData(patientExpendIncome);
	}

	@ApiOperation("患者端-收入支出")
	@PostMapping(value = "/consume/expendIncome")
	public APIResponse<UserExpendIncomeVO> patientExpendIncome(@RequestParam(required = false) String tdTime) {
		Long patientId =ShiroUtil.getLoginId();
		UserExpendIncomeVO patientExpendIncome = consumeDetailsSV.patientExpendIncome(patientId, tdTime);
		return successData(patientExpendIncome);
	}

	@ApiOperation("患者端-充值提现下单")
	@PostMapping(value = "/rechargeWithdraw")
	public APIResponse<PersonalTransactionOrderEntity> rechargeAndWithdraw(@RequestBody PersonalTransactionOrderEntity personalTransactionOrder) {
		Long patientId = ShiroUtil.getLoginId();
		//查询账户主键
		AccountEntity account = accountSV.selectAccountByUserId(patientId);
		if (TransactionDetailsTdTypeEnum.EMBODY.getKey().equals(personalTransactionOrder.getIoType())) {
			//判断账户余额
			if (account.getAccBalance().doubleValue() < personalTransactionOrder.getTdAmount().doubleValue()) {
				throw new BusinessException("提现金额不足");
			}
		}

		personalTransactionOrder.setAccId(account.getId());
		//订单编号
		personalTransactionOrder.setIoNum(generateCodeRuleSV.createCode(CodeRuleEnum.RECHARGE_WITHDRAW_ORDER));
		personalTransactionOrder.setPayState(PaymentStateEnum.TO_BE_PAID.getKey());
		personalTransactionOrder.setTdState(TransactionStateEnum.FOR_TRADING.getKey());
		personalTransactionOrderSV.insert(personalTransactionOrder);
		return successData(personalTransactionOrder);
	}

	@Log
	@ApiOperation("患者端-验证支付密码")
	@PostMapping(value = "/account/verifyPayPwd")
	public APIResponse verifyPaymentPassword(
			@Valid @RequestBody @NotNull Map<String,String> params
	) {
		UserEntity currentUser = SessionContext.getCurrUser();
		String oldPwdHash = ShiroUtil.genHashPass(params.get("pwd"), currentUser.getSalt());
		if (!oldPwdHash.equals(currentUser.getPayPwd())) {
			throw new BusinessException("支付密码不正确!");
		}
		return success();
	}

	@ApiOperation("患者端-设置支付密码接口")
	@PostMapping(value = "/account/setPayPwd")
	public APIResponse setPayPwd(
			@Valid @RequestBody UserSetPwdParam userSetPwdDTO
	) {
		UserEntity currentUser = SessionContext.getCurrUser();
		Boolean first = userSetPwdDTO.getFirst();
		UserEntity user = new UserEntity();
		String newPwd = ShiroUtil.genHashPass(userSetPwdDTO.getNewPwd(), currentUser.getSalt());
		if (first) {
			user.setId(currentUser.getId());
			user.setPayPwd(newPwd);
			userSV.updateById(user);
		} else {
			String oldPwdHash = ShiroUtil.genHashPass(userSetPwdDTO.getOldPwd(), currentUser.getSalt());
			if (!oldPwdHash.equals(currentUser.getPayPwd())) {
				throw new BusinessException("旧支付密码不正确!");
			}
			user.setId(currentUser.getId());
			user.setPayPwd(newPwd);
			userSV.updateById(user);
		}
		currentUser.setPayPwd(newPwd);
		userSV.refreshPatientUser();
		return success();
	}
}
